//
//  XFSegmentControl.m
//  FreeTime
//
//  Created by 王江华 on 16/9/12.
//  Copyright © 2016年 SRDZ.com. All rights reserved.
//

#import "XFSegmentControl.h"
#import "Header.h"
@implementation XFSegmentControl

{


    UIButton *_selectButton;
    

}
-(void)layoutSubviews{

    [super layoutSubviews];
    
    
    
    NSUInteger count=[self.titiles count];
    
    self.backgroundColor=[UIColor clearColor];
    
    CGFloat borderWidth = (self.layer.borderWidth == 0)?1.0f:self.layer.borderWidth;
    
    CGFloat width = self.frame.size.width  / count;
    for (int i=0; i<count; i++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(i * width, 0, width, self.frame.size.height)];
        
        
        [button setTitle:[self.titiles objectAtIndex:i] forState:UIControlStateNormal];
        
        [button setTitleColor:self.otherTextColor?self.otherTextColor:[ImageUtil colorWithRgb:0xe6e6e6] forState:UIControlStateNormal];
        
        [button setTitleColor:self.currentTextColor?self.currentTextColor:darkRed forState:UIControlStateSelected];
        
        [button setBackgroundImage:[UIImage imageNamed:[self.images objectAtIndex:i]] forState:0];
        
        button.titleLabel.font=self.currentFont?self.otherFont:[UIFont systemFontOfSize:13];
        
        [button setTag:i];
        
        //DLog(@"eew2%ld",self.currentIndex);
        
        if (i==self.currentIndex) {
            [self buttonClicked:button];
            
        }
        [button addTarget:self action:@selector(buttonClicked:) forControlEvents:1<<6];
        [self addSubview:button];
        
        CALayer *breaker = [CALayer layer];
        breaker.frame = CGRectMake(CGRectGetMaxX(button.frame), 0, borderWidth, self.frame.size.height);
        breaker.backgroundColor = self.borderColor.CGColor?self.borderColor.CGColor:[UIColor whiteColor].CGColor;
        [self.layer addSublayer:breaker];
    }

    
    
    

}
-(void)buttonClicked:(UIButton *)sender{
    
    if (sender != _selectButton) {
        sender.selected = YES;
        [sender setBackgroundColor:self.currentColor?self.currentColor:[UIColor whiteColor]];
        
        _selectButton.selected = NO;
        [_selectButton setBackgroundColor:self.otherColor?self.otherColor:[UIColor clearColor]];
        _selectButton = sender;
        
        NSLog(@"%ld",(long)sender.tag);
        if (self.segmentBlock) {
            self.segmentBlock(sender.tag);
            
        }
    }
}

@end
